package com.gblw.rjkf.pj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gblw.rjkf.pj.entity.SysMenus;
import com.gblw.rjkf.pj.entity.SysRole;
import com.gblw.rjkf.pj.mapper.SysMenusMapper;
import com.gblw.rjkf.pj.service.SysMenusService;
import com.gblw.rjkf.pj.utils.OtherUtils;
import com.gblw.rjkf.pj.utils.Result;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysMenusServiceImpl extends ServiceImpl<SysMenusMapper, SysMenus> implements SysMenusService {

    public Result buildMenuTree() {
        // 获取所有菜单
        List<SysMenus> allMenus = baseMapper.getAllMenus();

        // 创建一个映射，用于快速查找子菜单
        Map<Integer, SysMenus> menuById = allMenus.stream()
                .collect(Collectors.toMap(SysMenus::getId, menuItem -> menuItem));

        List<Map<String, Object>> menu = new ArrayList<>();

        for (SysMenus sysMenu : allMenus) {
            if (sysMenu.getParentId() == null) { // 只处理顶级菜单
                Map<String, Object> menuMap = new HashMap<>();
                menuMap.put("id",sysMenu.getId());
                // 检查顶级菜单是否有子菜单
                boolean hasChildren = !buildChildren(sysMenu.getId(), allMenus, menuById).isEmpty();

                // 如果顶级菜单有子菜单，则不包含 name 字段
                if (!hasChildren) {
                    menuMap.put("name", sysMenu.getName());
                }

                menuMap.put("text", sysMenu.getText());
                menuMap.put("type", sysMenu.getType());

                List<Map<String, Object>> children = buildChildren(sysMenu.getId(), allMenus, menuById);
                if (!children.isEmpty()) { // 只有当子菜单列表非空时才添加children字段
                    menuMap.put("children", children);
                }
                menu.add(menuMap);
            }
        }

        return Result.success("查询成功", menu);
    }

    @Override
    public Result Insert(SysMenus sysMenus) {
        sysMenus.setSize(18);
        QueryWrapper<SysMenus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("text", sysMenus.getText());
        List<SysMenus> list =baseMapper.selectList(queryWrapper);
        if(list.isEmpty()){
            int rs =baseMapper.insert(sysMenus);
            if (rs >0) {
                return Result.success("添加成功", "");
            } else {
                return Result.error("添加失败，稍后再试");
            }
        }else{
            return Result.error("添加失败,数据已经存在");

        }
    }

    @Override
    public Result update(SysMenus sysMenus) {

        // 获取当前要更新的记录的 ID 和 name
        Integer currentId = sysMenus.getId();
        String currentName = sysMenus.getName();

        // 创建查询包装器
        QueryWrapper<SysMenus> queryWrapper = new QueryWrapper<>();

        // 构建 OR 条件：name 存在，并且排除当前记录的 ID
        // 注意：这里需要确认 name 是否发生了变化
        queryWrapper.eq("text", sysMenus.getText())
                .ne(currentId != null && !currentName.equals(sysMenus.getText()), "id", currentId);

        // 执行查询
        List<SysMenus> list = baseMapper.selectList(queryWrapper);

        // 检查是否存在
        if (!list.isEmpty()) {
            return Result.error("该名称已存在，请检查");
        } else {
            // 更新记录
            baseMapper.updateById(sysMenus);
            return Result.success("更新成功", "");
        }
    }

    private List<Map<String, Object>> buildChildren(int parentId, List<SysMenus> allMenus, Map<Integer, SysMenus> menuById) {
        List<Map<String, Object>> children = new ArrayList<>();
        for (SysMenus menu : allMenus) {
            if (menu.getParentId() != null && menu.getParentId().equals(parentId)) {
                Map<String, Object> childMap = new HashMap<>();
                childMap.put("id",menu.getId());
                childMap.put("name", menu.getName()); // 子菜单包含 name 字段
                childMap.put("text", menu.getText());
                childMap.put("type", menu.getType());
                childMap.put("hidden", menu.getHidden());
                childMap.put("parentId",menu.getParentId());
                // 递归构建子菜单
                List<Map<String, Object>> subChildren = buildChildren(menu.getId(), allMenus, menuById);
                if (!subChildren.isEmpty()) { // 只有当子菜单列表非空时才添加children字段
                    childMap.put("children", subChildren);
                }
                children.add(childMap);
            }
        }
        return children;
    }



    public Result myselfMenuTree() {
        // 获取所有菜单
        SysRole sysRole = baseMapper.getRoleById(Integer.parseInt(StpUtil.getLoginId().toString()));

        QueryWrapper<SysMenus> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", OtherUtils.castInteger(sysRole.getMenuIds()));
        List<SysMenus> allMenus = baseMapper.selectList(queryWrapper);

        // 创建一个映射，用于快速查找子菜单
        Map<Integer, SysMenus> menuById = allMenus.stream()
                .collect(Collectors.toMap(SysMenus::getId, menuItem -> menuItem));

        List<Map<String, Object>> menu = new ArrayList<>();

        for (SysMenus sysMenus : allMenus) {
            if (sysMenus.getParentId() == null) { // 只处理顶级菜单
                Map<String, Object> menuMap = new HashMap<>();
                menuMap.put("id",sysMenus.getId());
                // 检查顶级菜单是否有子菜单
                boolean hasChildren = !buildChildren(sysMenus.getId(), allMenus, menuById).isEmpty();

                // 如果顶级菜单有子菜单，则不包含 name 字段
                if (!hasChildren) {
                    menuMap.put("name", sysMenus.getName());
                }

                menuMap.put("text", sysMenus.getText());
                menuMap.put("type", sysMenus.getType());

                List<Map<String, Object>> children = buildChildren(sysMenus.getId(), allMenus, menuById);
                if (!children.isEmpty()) { // 只有当子菜单列表非空时才添加children字段
                    menuMap.put("children", children);
                }
                menu.add(menuMap);
            }
        }

        return Result.success("查询成功", menu);
    }
}